'use strict';

const NodeRSA = require('node-rsa');
const publicKeyDataStart = '-----BEGIN PUBLIC KEY-----\n';
const publicKeyDataEnd = '\n-----END PUBLIC KEY-----';
const privateKeyDataStart = '-----BEGIN PRIVATE KEY-----\n';
const privateKeyDataEnd = '\n-----END PRIVATE KEY-----';


function encrypt(text, publicKeyData) {
    const key = new NodeRSA();
    key.setOptions({b: 1024, encryptionScheme: "pkcs1"});
    key.importKey(publicKeyData, 'pkcs8-public');
    const encrypted = key.encrypt(text, 'base64');
    return encrypted;
}


function decrypt(encrypted, privateKeyData) {
    const key = new NodeRSA();
    key.setOptions({b: 1024, encryptionScheme: "pkcs1"});
    key.importKey(privateKeyData, 'pkcs8-private');
    const decrypted = key.decrypt(encrypted, 'utf8');
    return decrypted;
}


function sign(text, privateKeyData) {
    const key = new NodeRSA();
    key.setOptions({b: 1024, signingScheme: "md5"});
    key.importKey(privateKeyData, 'pkcs8-private');
    const sign = key.sign(text, 'base64', 'utf8');
    return sign;
}


function verify(text, sign, publicKeyData) {
    const key = new NodeRSA();
    key.setOptions({b: 1024, signingScheme: "md5"});
    key.importKey(publicKeyData, 'pkcs8-public');
    const verify = key.verify(text, sign, 'utf8', 'base64');
    return verify;
}

exports.encrypt = encrypt;
exports.sign = sign;
exports.decrypt = decrypt;
exports.verify = verify;
